package com.xiejr.pss.jvm.classloader.demo;

import com.xiejr.pss.jvm.classloader.MyClassLoader;
import sun.misc.Launcher;

import java.util.ServiceLoader;

/**
 * @author mobai
 * @since 2021/5/20 16:00
 */
public class User {

    public User() {
        System.out.println("我是来自当前目录下的的的User");
    }

    static class MyClassLoaderSon extends MyClassLoader {

        public MyClassLoaderSon(String classPath) {
            super(classPath);
        }

        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            synchronized (getClassLoadingLock(name)) {
                // First, check if the class has already been loaded
                Class<?> c = findLoadedClass(name);
                if (c == null) {
                    if (!name.startsWith("com.xiejr")) {
                        c = getParent().loadClass(name);
                    } else {
                        c = findClass(name);
                    }

                }
                return c;
            }
        }
    }

    /**
     * 实现了同样一个User类，一个在类路径下，一个在外部磁盘，可以同时并存与jvm内存中
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        MyClassLoaderSon myClassLoader = new MyClassLoaderSon("/Users/mobai/Desktop");
        Thread.currentThread().setContextClassLoader(myClassLoader);
        Class<?> diskUser = myClassLoader.loadClass("com.xiejr.pss.jvm.classloader.demo.User");
        diskUser.newInstance();
        System.out.println(diskUser.getClassLoader());
        User user = new User();
        System.out.println(user.getClass().getClassLoader());
        System.out.println(diskUser == user.getClass());


    }
}
